package com.scuec.groupfive.controller;

import com.scuec.groupfive.entity.DailyTask;
import com.scuec.groupfive.service.DailyTaskService_eight;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/daily-tasks")
@CrossOrigin
public class DailyTaskController_eight {
    private static final Logger logger = LoggerFactory.getLogger(DailyTaskController_eight.class);

    @Autowired
    private DailyTaskService_eight dailyTaskService;

    private static final Map<String, String> STATUS_MAP = new HashMap<>();
    static {
        // 中文到英文的映射
        STATUS_MAP.put("未完成", "pending");
        STATUS_MAP.put("已完成", "completed");
        STATUS_MAP.put("已跳过", "skipped");

        // 英文到英文的映射（保持不变）
        STATUS_MAP.put("pending", "pending");
        STATUS_MAP.put("completed", "completed");
        STATUS_MAP.put("skipped", "skipped");
    }

    @GetMapping("/user/{username}")
    //http://localhost:8080/dailyTasks/user?username=student1
    public ResponseEntity<?> getTasksByUsername(
            @PathVariable String username,
            @RequestParam(required = false) String date) {
        try {
            List<DailyTask> tasks = dailyTaskService.getTasksByUsernameAndDate(username, date);
            return ResponseEntity.ok(tasks);
        } catch (Exception e) {
            return ResponseEntity.status(500).body(e.getMessage());
        }
    }

    @GetMapping("/list")
    //http://localhost:8080/dailyTasks/list
    public ResponseEntity<?> getListTasks() {
        try {
            List<DailyTask> tasks = dailyTaskService.getListTasks();
            return ResponseEntity.ok(tasks);
        } catch (Exception e) {
            return ResponseEntity.status(500).body(e.getMessage());
        }
    }

    @PutMapping("/update")
    public ResponseEntity<?> updateTaskStatus(@RequestBody DailyTask dailyTask) {
        try {
            int result = dailyTaskService.updateTaskStatus(dailyTask);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            return ResponseEntity.status(500).body(e.getMessage());
        }
    }

    @PostMapping("/add")
    public ResponseEntity<?> addDailyTask(@RequestBody DailyTask dailyTask) {
        logger.info("Received task request: {}", dailyTask);
        logger.info("Deep flag: {}, QuestionId: {}", dailyTask.getDeep(), dailyTask.getQuestionId());

        try {
            // 验证并转换状态值
            String status = dailyTask.getStatus();
            if (status != null) {
                String mappedStatus = STATUS_MAP.get(status);
                logger.info("Mapped status from '{}' to '{}'", status, mappedStatus);

                if (mappedStatus == null) {
                    logger.error("Invalid status value received: {}", status);
                    return ResponseEntity.badRequest().body("Invalid status value. Must be one of: 未完成, 已完成, 已跳过");
                }
                dailyTask.setStatus(mappedStatus);
            } else {
                dailyTask.setStatus("pending"); // 默认状态
                logger.info("Setting default task status to: pending");
            }

            // 验证状态值是否为有效的英文状态
            if (!isValidStatus(dailyTask.getStatus())) {
                logger.error("Invalid status value after mapping: {}", dailyTask.getStatus());
                return ResponseEntity.badRequest().body("Invalid status value. Must be one of: pending, completed, skipped");
            }

            // 如果设置了deep为true，则必须提供questionId
            if (Boolean.TRUE.equals(dailyTask.getDeep()) && dailyTask.getQuestionId() == null) {
                logger.error("Deep mode enabled but no questionId provided");
                return ResponseEntity.badRequest().body("在深度创建模式下必须提供questionId");
            }

            dailyTaskService.addDailyTask(dailyTask);
            return ResponseEntity.ok(dailyTask);
        } catch (Exception e) {
            logger.error("Failed to add task", e);
            return ResponseEntity.badRequest().body("Failed to add task: " + e.getMessage());
        }
    }

    private boolean isValidStatus(String status) {
        return status != null &&
                (status.equals("pending") ||
                        status.equals("completed") ||
                        status.equals("skipped"));
    }

    // 修改路径变量名：task_id -> taskId, user_id -> userId
    @DeleteMapping("/delete/{taskId}/{userId}")
    public ResponseEntity<?> deleteDailyTask(
            @PathVariable("taskId") Long taskId,
            @PathVariable("userId") Long userId) {
        try {
            int result = dailyTaskService.deleteDailyTask(taskId, userId);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            return ResponseEntity.status(500).body(e.getMessage());
        }
    }

    @GetMapping("/user/{username}/statistics")
    public ResponseEntity<?> getTaskStatisticsByUsername(@PathVariable String username) {
        try {
            Map<String, Object> statistics = dailyTaskService.getTaskStatisticsByUsername(username);
            return ResponseEntity.ok(statistics);
        } catch (Exception e) {
            logger.error("Error getting task statistics for user {}: {}", username, e.getMessage());
            return ResponseEntity.status(500).body("获取任务统计信息失败：" + e.getMessage());
        }
    }
}